package com.zmj.sy.mom.srv.aps.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

public class JacksonTool {
    /**
     * 对象转xml字符串
     *
     * @param o
     * @return
     * @throws JsonProcessingException
     */
    public static String java2Xml(Object o) throws JsonProcessingException {
        if (!Optional.ofNullable(o).isPresent()) {
            return null;
        }
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        return xmlMapper.writeValueAsString(o);
    }

    /**
     * xml字符串转对象
     *
     * @param o
     * @param cls
     * @param <T>
     * @return
     * @throws JsonProcessingException
     */
    public static <T> T xml2Java(String o, Class<T> cls) throws JsonProcessingException {
        if (StringUtils.isEmpty(o)) {
            return null;
        }
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        return xmlMapper.readValue(o, cls);
    }
}